package com.note.web;

import com.note.common.annotation.Log;
import com.note.common.core.controller.BaseController;
import com.note.common.core.domain.AjaxResult;
import com.note.common.core.domain.model.LoginUser;
import com.note.common.core.page.TableDataInfo;
import com.note.common.enums.BusinessType;
import com.note.common.utils.SecurityUtils;
import com.note.common.utils.StringUtils;
import com.note.common.utils.poi.ExcelUtil;
import com.note.config.SftpProperties;
import com.note.domain.NoteInfo;
import com.note.request.NoteSaveRequest;
import com.note.service.INoteInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

/**
 * 笔记controller
 * 
 * @author ruoyi
 * @date 2021-01-07
 */
@Api("笔记controller")
@Controller
@RequestMapping("/system/info")
public class NoteInfoController extends BaseController
{




    @Autowired
    private INoteInfoService noteInfoService;
    @Autowired
    private SftpProperties sftpProperties;

    /**
     * 查询【请填写功能名称】列表
     */
    @ResponseBody
    @ApiOperation("获取笔记列表")
    @GetMapping("/list")
    public TableDataInfo list(NoteInfo noteInfo)
    {
        startPage();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        noteInfo.setCreateUser(loginUser.getUser().getUserId());
        List<NoteInfo> list = noteInfoService.selectNoteInfoList(noteInfo);
        setUrlPrefix(list);
        return getDataTable(list);
    }


    /**
     * 设置文件预览的前缀和代理地址
     * @param list
     */
    private void setUrlPrefix(List<NoteInfo> list){
        if(CollectionUtils.isNotEmpty(list)){
            list.forEach(x -> {
                String previewUrl = x.getPreviewUrl();
                if(StringUtils.isNotEmpty(previewUrl)){
                    previewUrl = sftpProperties.getProxyHost()+File.separator+sftpProperties.getUrlPrefix()+File.separator+previewUrl;
                    x.setPreviewUrl(previewUrl);
                }
            });
        }
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @ResponseBody
    @PreAuthorize("@ss.hasPermi('system:info:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(NoteInfo noteInfo)
    {
        List<NoteInfo> list = noteInfoService.selectNoteInfoList(noteInfo);
        ExcelUtil<NoteInfo> util = new ExcelUtil<NoteInfo>(NoteInfo.class);
        return util.exportExcel(list, "info");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @ResponseBody
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(noteInfoService.selectNoteInfoById(id));
    }

    /**
     * 新增【请填写功能名称】
     */
    @ResponseBody
    @PreAuthorize("@ss.hasPermi('system:info:add')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody NoteInfo noteInfo)
    {
        return toAjax(noteInfoService.insertNoteInfo(noteInfo));
    }

    /**
     * 修改【请填写功能名称】
     */
    @ResponseBody
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody NoteInfo noteInfo)
    {
        return toAjax(noteInfoService.updateNoteInfo(noteInfo));
    }

    /**
     * 修改笔记详情
     */
    @ResponseBody
    @ApiOperation("修改笔记详情")
    @Log(title = "【修改笔记详情】", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    public AjaxResult update(NoteInfo noteInfo)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        noteInfo.setCreateDate(new Date());
        noteInfo.setCreateUser(loginUser.getUser().getUserId());
        noteInfoService.update(noteInfo);
        return AjaxResult.success();
    }

    /**
     * 获取笔记详情
     */
    @ResponseBody
    @ApiOperation("获取笔记详情")
    @Log(title = "【获取笔记详情】", businessType = BusinessType.UPDATE)
    @GetMapping
    public AjaxResult detail(@RequestParam Long noteId)
    {
        return AjaxResult.success(noteInfoService.detail(noteId));
    }


    /**
     * 批量删除笔记
     */
    @ResponseBody
    @ApiOperation("批量删除笔记")
    @Log(title = "【批量删除笔记】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(noteInfoService.deleteNoteInfoByIds(ids));
    }

    @ResponseBody
    @ApiOperation("上传笔记")
    @PostMapping("/save")
    public AjaxResult save(NoteSaveRequest noteSaveRequest, MultipartFile[] files) throws Exception {
        if((files == null || files.length == 0) && StringUtils.isBlank(noteSaveRequest.getText())){
            return AjaxResult.error("没有上传的内容");
        }

        LoginUser loginUser = SecurityUtils.getLoginUser();
        noteInfoService.saveNote(noteSaveRequest, loginUser, files);
        return AjaxResult.success("上传笔记成功");
    }



    @ApiOperation("导出笔记为HTML")
    @GetMapping("/exportToHtml")
    public void exportToHtml(@RequestParam Long noteId, HttpServletResponse response) throws Exception {
//        File htmlFile = noteInfoService.exportToHtml(noteId);
//        HttpHeaders headers = new HttpHeaders();
//        //为了解决中文名称乱码问题
//        String fileName = new String(htmlFile.getName().getBytes("UTF-8"),"iso-8859-1");
//        headers.setContentDispositionFormData("attachment", fileName);
//        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(htmlFile),
//                headers, HttpStatus.CREATED);

        File htmlFile = noteInfoService.exportToHtml(noteId);
        //设置响应头和客户端保存文件名
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + htmlFile.getName());

        try {
            //打开本地文件流
            InputStream inputStream =new FileInputStream(htmlFile);
            //激活下载操作
            OutputStream os = response.getOutputStream();

            //循环写入输出流
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }

            // 这里主要关闭。
            os.close();
            inputStream.close();
        } catch (Exception e){
            throw e;
        }


    }


}
